package org.swingplus.core.factory;

import org.swingplus.core.bean.DefinitionMetadata;
import org.swingplus.core.bean.RootBeanDefinition;
import org.swingplus.core.constant.bean.DependentOn;
import org.swingplus.core.exception.BeanCreateException;
import org.swingplus.core.scanner.ListenerScan;
import org.swingplus.core.scanner.OrderScan;
import org.swingplus.core.scanner.WidgetScan;
import org.swingplus.core.util.AnnoManageUtil;
import org.swingplus.core.utils.ClassFileInfoParseUtil;
import org.swingplus.core.utils.ObjectConvertUtil;
import org.swingplus.core.utils.StringUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AbstractAutowireBeanFactory extends AbstractBeanFactory {

    public final static List<Class> constructorSingletonObjectsClass = new ArrayList<>();
    public final static List<Class> fieldsSingletonObjectsClass = new ArrayList<>();

    public final static Map<String, Object> constructorSingletonObjects = new ConcurrentHashMap<String, Object>(256);

    public final static Map<String, Object> fieldsSingletonObjects = new ConcurrentHashMap<String, Object>(256);


    @Override
    public Object createBean(String beanName, RootBeanDefinition mbd) throws BeanCreateException {
        Object obj = null;

        obj = getSingletion(beanName);
        if(null!=obj){
            return obj;
        }
        obj = getEarlySingletonObjects(beanName);
        if(null!=obj){
            return obj;
        }


        Class clazz = mbd.getBeanClass();

        //first choice setter or constructor in BeanCreate
        if (mbd.getDependentOn().equals(DependentOn.SETTTER.toString())) {
//			@SuppressWarnings("unchecked")
            obj = WidgetFactroy.create(mbd.getBeanClass().getTypeName());
            setEarlySingletonObjects(beanName, obj);
            setSingletonCurrentlyInCreation(beanName);
            if (AnnoManageUtil.existAutowiredConstructors(mbd.getAutowiredField())) {

                setEarlySingletonObjects(beanName, obj);

                Field[] fields = mbd.getAutowiredField();
                for (Field field : fields) {
                    DefinitionMetadata dm = ClassFileInfoParseUtil.getDefinitionMetadata(field.getType());
                    RootBeanDefinition rbd = ObjectConvertUtil.definitionMetadataToRootBeanDefinition(dm);
                    createBean(field.getName(), rbd);
                }
//	    	    	Constructor[] constructors = AnnoManageUtil.autowiredConstructors(mbd.getAutowiredField());
//	    	    	for (Constructor constructor : constructors) {
//	    	    		createBean();
//					}
            }
            if (mbd.getExistsAutowired()) {
                Field[] fields = mbd.getAutowiredField();
                for (Field field : fields) {
                    Object object = getSingletion(field.getName());
                    if (object == null && isSingletonCurrentlyInCreation(beanName)) {
//                        setSingletonCurrentlyInCreation(field.getName());
//                        setEarlySingletonObjects(beanName,obj);
                        DefinitionMetadata dm = ClassFileInfoParseUtil.getDefinitionMetadata(field.getType());
                        RootBeanDefinition rbd = ObjectConvertUtil.definitionMetadataToRootBeanDefinition(dm);
                        object = createBean(field.getName(), rbd);
//                        object = WidgetFactroy.create(mbd.getBeanClass().getTypeName());

//						object = getSingletion(field.getName());
                        if (object == null) {
                            throw new BeanCreateException("no find Bean name:" + field.getName() + "Type:" + field.getType());
                        } else {
                            try {
                                boolean flag = field.isAccessible();
                                field.setAccessible(true);
                                field.set(obj, object);
                                field.setAccessible(flag);
                            } catch (IllegalArgumentException | IllegalAccessException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    } else {
                        try {
                            boolean flag = field.isAccessible();
                            field.setAccessible(true);
                            field.set(obj, object);
                            field.setAccessible(flag);
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                }
                addSingletonObjects(beanName, obj);
                removeEarlySingletonObjects(beanName);
            }
        } else {
            if (AnnoManageUtil.existAutowiredConstructors(mbd.getAutowiredField())) {
//				setEarlySingletonObjects(beanName,obj);
                Field[] fields = mbd.getAutowiredField();
                for (Field field : fields) {
                    DefinitionMetadata dm = ClassFileInfoParseUtil.getDefinitionMetadata(field.getType());
                    RootBeanDefinition rbd = ObjectConvertUtil.definitionMetadataToRootBeanDefinition(dm);
                    createBean(field.getName(), rbd);
                }
            }

            // if exist constructors autowired field
//			if (AnnoManageUtil.existAutowiredConstructors(clazz)) {
            Constructor[] constructors = AnnoManageUtil.autowiredConstructors(clazz);
            for (Constructor constructor : constructors) {
//					constructor.getParameterTypes()
                try {
                    Class<?>[] parameterTypes = constructor.getParameterTypes();
                    //Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
                    Object[] argsWithDefaultValues = new Object[parameterTypes.length];

                    for (int i = 0; i < parameterTypes.length; i++) {
                        String beanNameStr = StringUtil.lowerFirst(parameterTypes[i].getName());
                        Object object = getSingletion(beanNameStr);
                        if (object == null) {
                            object = getEarlySingletonObjects(beanNameStr);
                            if (object == null) {
                                throw new BeanCreateException("no find Bean name:" + beanNameStr + "Type:" + parameterTypes[i]);
                            } else {
                                argsWithDefaultValues[i] = object;
                            }
                        } else {
                            argsWithDefaultValues[i] = object;
                        }

                        obj = constructor.newInstance(argsWithDefaultValues);
                        addSingletonObjects(beanNameStr, obj);
                    }

                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                        | InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {

                }

            }


        }
        if (obj != null) {
            try {
                WidgetScan.widgetScan(obj);
                ListenerScan.listenerScan(obj);

                OrderScan.orderScan(obj);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        removeSingletonCurrentlyInCreation(beanName);

        return obj;
    }

    @Override
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args) {

        return null;
    }

}
